
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;

/*
 * GingaTestGUI.java
 *
 * Created on 27/11/2011, 11:04:55
 */

/**
 *
 * @author dbarreto
 */
public class GingaTestGUI extends javax.swing.JFrame {

    private Listener list;
    /** Creates new form GingaTestGUI */
    public GingaTestGUI() {

        initComponents();

        list = new Listener(8080, txtMsgRecv, txtMsgEnv);
        list.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnSend = new javax.swing.JButton();
        txtMsgEnv = new javax.swing.JTextField();
        lblMsg = new javax.swing.JLabel();
        lblMsgSnd = new javax.swing.JLabel();
        txtMsgRecv = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnSend.setText("Enviar");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        lblMsg.setText("Mensagem recebida:");

        lblMsgSnd.setText("Mensagem a enviar:");

        txtMsgRecv.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMsgSnd)
                    .addComponent(lblMsg))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtMsgEnv, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtMsgRecv, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblMsgSnd)
                    .addComponent(txtMsgEnv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblMsg)
                    .addComponent(txtMsgRecv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed

        list.setSendText(txtMsgEnv.getText());
    }//GEN-LAST:event_btnSendActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GingaTestGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSend;
    private javax.swing.JLabel lblMsg;
    private javax.swing.JLabel lblMsgSnd;
    private javax.swing.JTextField txtMsgEnv;
    private javax.swing.JTextField txtMsgRecv;
    // End of variables declaration//GEN-END:variables

}

class Listener extends Thread {

    private int port;
    private String lastMsg;
    private ServerSocket server;
    private Socket socket;
    private JTextField rec;
    private JTextField env;
    private String sndMsg;

    Listener(int port, JTextField rec, JTextField env) {

        this.rec = rec;
        this.env = env;
        this.port = port;
        this.sndMsg = "";
    }

    public void run() {
        try {
            server = new ServerSocket(port);
        } catch (IOException ex) {
            Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
        }

        while (true) {
            try {

                socket = server.accept();

                //cria objetos para leitura e escrita no socket
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                System.out.println("Esperando mensagem...");

                //le mensagem do socket
                lastMsg = in.readLine();

                System.out.println("Mensagem recebida: " + lastMsg);

                if (!lastMsg.contains("hasMsg"))
                    rec.setText(lastMsg);

                //if (sndMsg == "")
                    //sndMsg = "null";

                out.println(sndMsg);
                System.out.println("Mensagem enviada: " + sndMsg);

                sndMsg = "";
                socket.close();

            } catch (IOException ex) {
                Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public String getMessage() {
        return lastMsg;
    }

    void setSendText(String text) {
        sndMsg = text;
    }

}
